#include "Drawable.h"

using namespace Graphics;

Drawable::Drawable(Renderable* parent, bool d):Renderable(parent, d)
{
}

void Drawable::managedRedraw()
{
	if (!_dynamic)
	{
		if (_id<1)
			createID();

		glNewList(_id,GL_COMPILE);
	}

	//Set default color
	glColor3f(1.0f,1.0f,1.0f);

	//Specify texture
	if (_texture && _texture->id()>0)
	{
		glEnable(GL_CULL_FACE);
		glCullFace(GL_BACK);
		glEnable(GL_TEXTURE_2D);

		glBindTexture(GL_TEXTURE_2D,_texture->id());
		if (_texture->modulate())
			glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
		else
			glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

	}

	//Set position
	glTranslatef((GLfloat)_position.x(),(GLfloat)_position.y(),(GLfloat)_position.z());
	//Set rotation
	glRotatef((GLfloat)_rotation.angle(),(GLfloat)_rotation.direction()->x(),(GLfloat)_rotation.direction()->y(),(GLfloat)_rotation.direction()->z());

		redraw();


	//Specify texture
	if (_texture && _texture->id()>0)
	{
		glDisable(GL_TEXTURE_2D);
		glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
	}

	if (!_dynamic)
	{
		glEndList();
		_redraw=false;
	}
}

void Drawable::draw()
{
	//Save current matrix
	glPushMatrix();

	if (_dynamic || _redraw)
		managedRedraw();

	if (_id)
		render();

	//Only render children if there are any
	if (!_children.empty())
	{

		//Loop through all the children and call their draw() method
		ListT::iterator it;

	//	_children.reverse();
		for (it=_children.begin();it!=_children.end();++it)
			(*it)->draw();

	//	_children.reverse();
	}

	//Restore the matrix
	glPopMatrix();
}
